package com.sgai.zero_robot.core.io;

import android.serialport.SerialPort;
import com.sgai.zero_robot.core.Protocol;
import com.sgai.zero_robot.core.callback.ReceveCallback;
import com.sgai.zero_robot.core.callback.LogCallback;
import com.sgai.zero_robot.utils.LogUtil;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
public class RobotSerialManager {
    private SerialPort serialPort;
    private final String TAG = "RobotSerialManager";
    private ReadHandler readHandler;
    private AtomicBoolean running = new AtomicBoolean(false);
    private WriteHandler writeHandler;

    /**
     * 打开串口
     */
    public boolean open(String device, int baudRate, ReceveCallback callback) {
        LogUtil.e(TAG,"open  "+running.get());
        if (running.get()){
            return true;
        }
        try {
            serialPort = new SerialPort(new File(device), baudRate);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        running.set(true);
        readHandler = new ReadHandler(serialPort.getInputStream(),callback);
        writeHandler = new WriteHandler(serialPort.getOutputStream());
        LogUtil.d(TAG,"✅ 串口已打开: " + device + " 波特率: " + baudRate);
        return true;
    }

    /**
     * 关闭串口
     */
    public void close() {
        LogUtil.e(TAG,"close  "+running.get());
        if (running.get()){
            running.set(false);
            if (readHandler!=null){
                readHandler.close();
            }
            if (writeHandler!=null){
                writeHandler.close();
            }

            if (serialPort != null) serialPort.close();
            LogUtil.d(TAG,"🔒 串口已关闭");
        }
    }

    /**
     * 发送数据
     */
    public void send(byte[] data) {
        LogUtil.e(TAG,"send");
        if (writeHandler != null) {
            writeHandler.sendMessage(data);
            LogUtil.d(TAG,"➡️ 发送: " + Protocol.bytesToHex(data));
        }
    }
    public void setLogCallback(LogCallback logcallback) {
        if (readHandler!=null){
            readHandler.setLogCallback(logcallback);
        }
    }

    public void removeLogCallback() {
        if (readHandler!=null){
            readHandler.removeLogCallback();
        }
    }
}
